package com.ybkj.daijia.api.member.v3;

import com.ybkj.daijia.api.member.ErrorConstant;
import com.ybkj.daijia.api.member.SecurityUtils;
import com.ybkj.daijia.api.member.transport.ResultTransport;
import com.ybkj.daijia.page.Page;
import com.ybkj.daijia.server.mc.Passenger;
import com.ybkj.daijia.server.sales.Coupon;
import com.ybkj.daijia.server.sales.CouponRule;
import com.ybkj.daijia.server.service.CouponService;
import com.ybkj.daijia.server.service.MemberService;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller("CouponV3Controller")
@RequestMapping(value = "member/api/rest/v3")
public class CouponController {

    private static final Logger logger = LoggerFactory.getLogger(CouponController.class);

    @Autowired
    private CouponService couponService;

    @Autowired
    private MemberService memberService;

    /**
     * 查询优惠劵
     *
     * @param phone
     * @param page
     * @param limit
     * @param appKey
     * @param token
     * @param timestamp
     * @return
     */
    @RequestMapping(value = "queryCoupons", method = RequestMethod.POST)
    public @ResponseBody
    ResultTransport queryCoupons(String phone, Integer page, Integer limit, String appKey,
        String token, String timestamp) {

        logger.debug("recv phone:{},page:{},limit:{},appKey:{},token:{},timestamp:{}", phone, page,
            limit, appKey, token, timestamp);

        if (StringUtils.isBlank(phone) || SecurityUtils.isBlank(appKey, token, timestamp)) {
            return ResultTransport.getErrorBy(ErrorConstant.PARAM_ERROR);
        }

//		if(!StringUtils.isNumeric(timestamp) || !SecurityUtils.checkTimestamp(Long.parseLong(timestamp))) {
//			return ResultTransport.getErrorBy(ErrorConstant.TIMESTAMP_ERROR);
//		}

        List<String> params = new LinkedList<String>();
        params.add(String.valueOf(phone));
        params.add(String.valueOf(page));
        params.add(String.valueOf(limit));
        params.add(timestamp);
        params.add(appKey);

        if (!SecurityUtils.checkToken(params, token)) {
            return ResultTransport.getErrorBy(ErrorConstant.TOKEN_ERROR);
        }

        Passenger passenger = memberService.findOnePassengerByPhone(phone);

        if (null == passenger) {
            return ResultTransport.getErrorBy(ErrorConstant.MEMBER_NOT_EXISTS_ERROR);
        }

        try {

            Page<Coupon> pageCoupons = couponService
                .queryByPassenger(passenger.getId(), page, limit, null);

            ResultTransport instance = ResultTransport.getErrorBy(ErrorConstant.SUCCESS);
            instance.setData(pageCoupons);

            return instance;

        } catch (Exception e) {
            logger.error("api v3 queryCoupons error: {}", e);
            return ResultTransport.getErrorBy(ErrorConstant.SERVER_ERROR);
        }

    }

    /**
     * 微信公众号V5分页查询优惠劵
     *
     * @param phone  电话
     * @param page   页码
     * @param limit  条数
     * @param status 优惠券状态 0未绑定 1未用(已绑定) 2已用 3失效
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "queryCouponsV5", method = RequestMethod.POST)
    public ResultTransport queryCouponsV5(
        @RequestParam(required = true, value = "phone") String phone,
        @RequestParam(required = true, value = "page") Integer page,
        @RequestParam(required = true, value = "limit") Integer limit,
        @RequestParam(required = false, value = "status") Integer status) {

        if (StringUtils.isBlank(phone)) {
            return ResultTransport.getErrorBy(ErrorConstant.PARAM_ERROR);
        }

        Passenger passenger = memberService.findOnePassengerByPhone(phone);

        if (null == passenger) {
            return ResultTransport.getErrorBy(ErrorConstant.MEMBER_NOT_EXISTS_ERROR);
        }

        try {

            Page<Coupon> pageCoupons = couponService
                .queryByPassenger(passenger.getId(), page, limit, status);
            ResultTransport instance = ResultTransport.getErrorBy(ErrorConstant.SUCCESS);
            instance.setData(pageCoupons);
            return instance;

        } catch (Exception e) {
            logger.error("api v3 queryCoupons error: {}", e);
            return ResultTransport.getErrorBy(ErrorConstant.SERVER_ERROR);
        }
    }


    @RequestMapping(value = "queryAllCoupons", method = RequestMethod.POST)
    public @ResponseBody
    ResultTransport queryAllCoupons(String phone, String appKey, String token, String timestamp) {

        logger.debug("recv phone:{},appKey:{},token:{},timestamp:{}", phone, appKey, token,
            timestamp);

        if (StringUtils.isBlank(phone) || SecurityUtils.isBlank(appKey, token, timestamp)) {
            return ResultTransport.getErrorBy(ErrorConstant.PARAM_ERROR);
        }

        List<String> params = new LinkedList<String>();
        params.add(String.valueOf(phone));
        params.add(timestamp);
        params.add(appKey);

        if (!SecurityUtils.checkToken(params, token)) {
            return ResultTransport.getErrorBy(ErrorConstant.TOKEN_ERROR);
        }

        Passenger passenger = memberService.findOnePassengerByPhone(phone);

        if (null == passenger) {
            return ResultTransport.getErrorBy(ErrorConstant.MEMBER_NOT_EXISTS_ERROR);
        }

        try {

            List<Coupon> coupons = couponService
                .listByPassenger(passenger.getId(), null, null, null);

            List<Map<String, Object>> mapList = new ArrayList<Map<String, Object>>();
            if (!CollectionUtils.isEmpty(coupons)) {
                for (Coupon coupon : coupons) {
                    CouponRule couponRule = coupon.getCouponRule();
                    Map<String, Object> map = new HashMap<String, Object>();
                    map.put("couponId", coupon.getId());
                    map.put("couponMoney", couponRule.getMoney());
                    map.put("couponCode", coupon.getCode());
                    map.put("couponStatus", coupon.getStatus());
                    map.put("couponTitle", couponRule.getTitle());
                    map.put("startTime", couponRule.getStart().getTime());
                    map.put("startDate", couponRule.getStart());
                    if (null != couponRule.getEnd()) {
                        map.put("endTime", couponRule.getEnd().getTime());
                        map.put("endDate", couponRule.getEnd());
                    }

                    mapList.add(map);
                }
            }

            ResultTransport instance = ResultTransport.getErrorBy(ErrorConstant.SUCCESS);
            instance.setData(mapList);

            return instance;

        } catch (Exception e) {
            logger.error("api v3 queryAllCoupons error: {}", e);
            return ResultTransport.getErrorBy(ErrorConstant.SERVER_ERROR);
        }

    }


    @RequestMapping(value = "couponBind", method = RequestMethod.POST)
    public @ResponseBody
    ResultTransport couponBind(String phone, String code, String codeKey, String appKey,
        String token, String timestamp) {

        logger
            .debug("recv phone:{},code:{},codeKey:{},appKey:{},token:{},timestamp:{}", phone, code,
                codeKey, appKey, token, timestamp);

        if (StringUtils.isBlank(phone) || StringUtils.isBlank(code) || StringUtils.isBlank(codeKey)
            || SecurityUtils.isBlank(appKey, token, timestamp)) {
            return ResultTransport.getErrorBy(ErrorConstant.PARAM_ERROR);
        }

//		if(!StringUtils.isNumeric(timestamp) || !SecurityUtils.checkTimestamp(Long.parseLong(timestamp))) {
//			return ResultTransport.getErrorBy(ErrorConstant.TIMESTAMP_ERROR);
//		}

        List<String> params = new LinkedList<String>();
        params.add(String.valueOf(phone));
        params.add(String.valueOf(code));
        params.add(String.valueOf(codeKey));
        params.add(timestamp);
        params.add(appKey);

        if (!SecurityUtils.checkToken(params, token)) {
            return ResultTransport.getErrorBy(ErrorConstant.TOKEN_ERROR);
        }

        Passenger passenger = memberService.findOnePassengerByPhone(phone);

        if (null == passenger) {
            return ResultTransport.getErrorBy(ErrorConstant.MEMBER_NOT_EXISTS_ERROR);
        }

        Coupon coupon = couponService.findByCode(code);
        if (null == coupon) {
            return ResultTransport.getErrorBy(ErrorConstant.COUPON_NOT_EXISTS_ERROR);
        }

        if (!coupon.getStatus().equals(Coupon.COUPON_STATUS_NOTBIND)) {
            return ResultTransport.getErrorBy(ErrorConstant.COUPON_STATUS_ERROR);
        }

        if (!coupon.getCodeKey().equals(codeKey)) {
            return ResultTransport.getErrorBy(ErrorConstant.COUPON_CODEKEY_ERROR);
        }

        try {

            coupon.setPassengerId(passenger.getId());
            coupon.setPhone(phone);
            coupon.setStatus(Coupon.COUPON_STATUS_NOTUSE);//未用（已绑定）
            couponService.update(coupon);

            ResultTransport instance = ResultTransport.getErrorBy(ErrorConstant.SUCCESS);

            return instance;

        } catch (Exception e) {
            logger.error("api v3 couponBind error: {}", e);
            return ResultTransport.getErrorBy(ErrorConstant.SERVER_ERROR);
        }

    }

    /**
     * V5微信公众号添加优惠券
     *
     * @param phone   电话
     * @param code    优惠券码
     * @param codeKey 优惠券密码
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "couponBindV5", method = RequestMethod.POST)
    public ResultTransport couponBindV5(String phone, String code, String codeKey) {

        if (StringUtils.isBlank(phone) || StringUtils.isBlank(code) || StringUtils
            .isBlank(codeKey)) {
            return ResultTransport.getErrorBy(ErrorConstant.PARAM_ERROR);
        }

        Passenger passenger = memberService.findOnePassengerByPhone(phone);
        if (null == passenger) {
            return ResultTransport.getErrorBy(ErrorConstant.MEMBER_NOT_EXISTS_ERROR);
        }

        Coupon coupon = couponService.findByCode(code);
        if (null == coupon) {
            return ResultTransport.getErrorBy(ErrorConstant.COUPON_NOT_EXISTS_ERROR);
        }

        if (!coupon.getStatus().equals(Coupon.COUPON_STATUS_NOTBIND)
            || coupon.getCouponRule().getTimeStatus()
            .equals(CouponRule.COUPONRULE_STATUS_OVERDUE)) {
            return ResultTransport.getErrorBy(ErrorConstant.COUPON_STATUS_ERROR);
        }

        if (!coupon.getCodeKey().equals(codeKey)) {
            return ResultTransport.getErrorBy(ErrorConstant.COUPON_CODEKEY_ERROR);
        }

        try {

            coupon.setPassengerId(passenger.getId());
            coupon.setPhone(phone);
            coupon.setStatus(Coupon.COUPON_STATUS_NOTUSE); //未用（已绑定）
            couponService.update(coupon);
            ResultTransport instance = ResultTransport.getErrorBy(ErrorConstant.SUCCESS);
            return instance;

        } catch (Exception e) {
            logger.error("api v3 couponBind error: {}", e);
            return ResultTransport.getErrorBy(ErrorConstant.SERVER_ERROR);
        }

    }

}
